package xyz.scootaloo.mono.admin.service

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import xyz.scootaloo.mono.admin.dto.MenuItemVO
import xyz.scootaloo.mono.data.cache.MenuCacheManager
import xyz.scootaloo.mono.data.entity.auth.AuthMenu
import xyz.scootaloo.mono.security.service.AccountService

/**
 * 获取用户信息
 * 获取用户菜单
 *
 * @author flutterdash@qq.com
 * @since 2021/9/10 15:15
 */
@Service
class UIService {

    @Autowired private lateinit var accountService: AccountService

    fun getUserMenu(): List<MenuItemVO> {
        val client = accountService.getCurrentClient()
        val menuItems = MenuCacheManager.getItemsOf(client.roleCode)
        return weave(menuItems)
    }

    private fun weave(menuItems: List<AuthMenu>): List<MenuItemVO> {
        val rootNodes = HashMap<Int, MenuItemVO>()
        val leafNodes = ArrayList<AuthMenu>()
        for (item in menuItems) {
            if (item.parent == 0) {
                rootNodes[item.id] = item.toVO()
            } else {
                leafNodes.add(item)
            }
        }

        for (leaf in leafNodes) {
            rootNodes[leaf.parent]?.children?.add(leaf.toVO())
        }

        return rootNodes.values.toList()
    }

    private fun AuthMenu.toVO(): MenuItemVO {
        return MenuItemVO(
            key = this.path,
            title = this.name,
            icon = this.icon,
            isLeaf = this.parent == 0
        )
    }
}
